import dd from 'gdt-jsapi'
import * as services from '../../services/index'
import globalData from '../../globalData'

Page({
  data: {
    globalData,
    detail: {},
    userInfo: {},
    totalDeductMarks: 0,
    remediationAfterPhotoUrl: ''
  },

  async onLoad(query) {
    console.log(1, query)
    const userInfo = await services.getUserInfo()
    this.setData({ userInfo })
    this.getRemediationDetail({ remediationId: query.remediationId })
    // 页面加载
  },
  async getRemediationDetail(params) {
    const { data } = await services.getRemediation(params)
    this.setData({
      detail: data,
      totalDeductMarks: (data.remediationDetail || []).reduce((total, item) => total = total + Number(item.deductMarks), 0)
    })
    console.log(data)
  },
  previewImage(e) {
    my.previewImage({
      current: this.data.detail.photoUrl,
      urls: [this.data.detail.photoUrl, this.data.detail.remediationAfterPhotoUrl],
    })
  },
  // 上传图片
  selectImage() {
    my.chooseImage({
      chooseImage: 1,
      success: async res => {
        const path = res.apFilePaths[0];
        const image = await services.uploadFile({ filePath: path });
        this.setData({ remediationAfterPhotoUrl: image })
      },
    })
  },

  handleApprove(type) {
    const title = type === 1 ? '确认退回' : '确认审核通过';
    const buttonLabels = ["确认", "取消"];
    dd.confirm({ title, buttonLabels }).then(async ({ buttonIndex }) => {
      if (buttonIndex === 0) {
        const { code } = services.approve({
          remediationId: this.data.detail.remediationId,
          // 审核类型（1. 审核通过；2. 退回）
          approveType: type === 1 ? 2 : 1,
          remark: ''
        })
        if (code === 200) {
          await dd.showToast({ type: "success", content: "提交成功", duration: 1000 })
          dd.navigateBack({ delta: 1 })
        }
      }
    });
  },

  handleReturn() { this.handleApprove(1) },
  handlePass() { this.handleApprove(2) },

  async handleSubmit() {
    if (this.data.remediationAfterPhotoUrl === 0) {
      dd.showToast({ content: "请上传整改后照片", duration: 1000 })
      return
    }
    const { code, message } = await services.submitRemediationByPLocOwner({
      remediationId: this.data.detail.remediationId,
      remediationAfterPhotoUrl: [this.data.remediationAfterPhotoUrl],
      employeeCode: this.data.userInfo.employeeCode
    })
    if (code === 200) {
      await dd.showToast({ type: "success", content: "提交成功", duration: 500 })
      dd.navigateBack({ delta: 1 })
    } else {
      dd.showToast({ content: message, duration: 500 })
    }
  }
});
